import type { Router, RouteRecordRaw, RouterHistory } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "@/stores/user";

class RouteView {
  // 根据环境变量中的配置生成路由模式
  public static createHistory = (): RouterHistory => {
    return createWebHashHistory();
  };

  // 动态获取 modules 目录下的所有 .ts 文件生成基础路由
  public static createBasicRoutes = (): RouteRecordRaw[] => {
    const moduleFiles: { [key: string]: any } = import.meta.glob(
      "./modules/**/*.ts",
      {
        eager: true,
      },
    );
    const routeModuleList: RouteRecordRaw[] = [];
    Object.keys(moduleFiles).forEach((key) => {
      const mod: { [key: string]: any } = moduleFiles[key].default || {};
      const modList: RouteRecordRaw[] = Array.isArray(mod) ? [...mod] : [mod];
      routeModuleList.push(...modList);
    });

    return routeModuleList;
  };

  // 创建路由对象
  public static createRouter(): Router {
    return createRouter({
      history: RouteView.createHistory(),
      routes: RouteView.createBasicRoutes(),
      strict: true,
      scrollBehavior: () => ({ left: 0, top: 0 }),
    });
  }

  // 路由对象
  private router: Router | unknown = undefined;

  public constructor() {
    this.router = RouteView.createRouter();
    this.beforeRouteChange();
    this.afterRouteChange();
  }

  // 获取路由对象
  public getRouter(): Router {
    return this.router as Router;
  }

  // 路由守卫
  private beforeRouteChange(): void {
    if (!this.router) {
      return;
    }

    const curRouter = this.router as Router;
    curRouter.beforeEach((to, _, next) => {
      next();
    });
  }

  private afterRouteChange(): void {
    if (!this.router) {
      return;
    }

    const curRouter = this.router as Router;
    curRouter.afterEach((to, _from, _failure) => {
      if (to.path !== "/login") {
        useUserStore().setUserInfo();
      }
    });
  }
}

const router = new RouteView();

export default router.getRouter();
